#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFile>
#include <QFileDialog>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->setupUi(this);
    setupEditor();

    QMenu *fileMenu = menuBar()->addMenu("File");
    QAction *openAction = new QAction("Open", this);
    connect(openAction, &QAction::triggered, this, &MainWindow::openFile);
    fileMenu->addAction(openAction);

    QMenu *viewMenu = menuBar()->addMenu("View");
    QAction *zoomInAction = new QAction("Zoom In", this);
    connect(zoomInAction, &QAction::triggered, this, &MainWindow::zoomIn);
    viewMenu->addAction(zoomInAction);

    QAction *zoomOutAction = new QAction("Zoom Out", this);
    connect(zoomOutAction, &QAction::triggered, this, &MainWindow::zoomOut);
    viewMenu->addAction(zoomOutAction);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::openFile()
{
    QString filePath = QFileDialog::getOpenFileName(this, "Open File");
    if (!filePath.isEmpty()) {
        QFile file(filePath);
        if (file.open(QFile::ReadOnly | QFile::Text)) {
            QTextStream in(&file);
            // 指定编码格式
            in.setAutoDetectUnicode("UTF-8");
            QString content = in.readAll();
            editor->setPlainText(content);
            file.close();
        } else {
            qDebug() << "Failed to open file:" << filePath;
        }
    }
}
// 在MainWindow类中添加缩放功能的槽函数
void MainWindow::zoomIn()
{
    QFont font = editor->font();
    font.setPointSize(font.pointSize() + 1);
    editor->setFont(font);
}

void MainWindow::zoomOut()
{
    QFont font = editor->font();
    if (font.pointSize() > 1) {
        font.setPointSize(font.pointSize() - 1);
        editor->setFont(font);
    }
}


void MainWindow::setupEditor()
{
    QFont font;
    font.setFamily("Courier");
    font.setFixedPitch(true);
    font.setPointSize(10);

    editor = new CodeEditor();
    editor->setFont(font);

    highlighter = new Highlighter(editor->document());

    QFile file("mainwindow.h");
    if (file.open(QFile::ReadOnly | QFile::Text))
        editor->setPlainText(file.readAll());

    // 将 editor 添加到主窗口的中心部件
    setCentralWidget(editor);
}
